#include "aliyun.h"

/*文件内部使用的宏*/
//MQTT服务器的domain地址
#define ALIYUN_SERVER "a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com"
//MQTT服务器的port端口
#define ALIYUN_PORT 1883
//client端标识符
#define MQTT_CLIENT_ID "12345|securemode=3,signmethod=hmacsha1|"
//用户账号
#define MQTT_USERNAME "ESP32_LED&a1ay7f9DL7I"
//用户密码
#define MQTT_PASSWORD "0922F148DAAA0E418ED49533979B0240603CDBD5"
//阿里云设备上报属性请求Topic
#define ALIYUN_UPDATE_TOPIC "/sys/a1ay7f9DL7I/ESP32_LED/thing/event/property/post"

/*本地变量*/
WiFiClient espclient;
static bool connect_to_aliyun_flag = false;

/*全局变量*/
PubSubClient client(espclient);

void Connect_To_Aliyun(void)
{
    client.setServer(ALIYUN_SERVER,ALIYUN_PORT);
    while(!client.connect(MQTT_CLIENT_ID,MQTT_USERNAME,MQTT_PASSWORD))
    {
        Serial.println("No connect to Aliyun");
    }

    connect_to_aliyun_flag = true;

    Serial.println("Connect To aliyun success");
    Serial.printf("Aliyun.cpp %d:%d\r\n",__LINE__,esp_get_free_heap_size());
    // client.connect(MQTT_CLIENT_ID,MQTT_USERNAME,MQTT_PASSWORD);
    // if(client.connected())
    // {
    //     Serial.println("client connects Aliyun success first");
    //     Serial.printf("ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
    // }
    // else
    // {
        
    // }
}

void Aliyun_Loop(void)
{
    // if(client.connected())
    // {
    //     client.loop();
    // }
    if(connect_to_aliyun_flag == true)
    {
        client.loop();
    }
    //Serial.printf("ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
}

void Disconnect_To_Aliyun(void)
{
    if(connect_to_aliyun_flag == true)
    {
        client.disconnect();
        Serial.println("Disconnect To Aliyun success");
        Serial.printf("Aliyun.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());
        connect_to_aliyun_flag = false;
    }
}

void Update_Id_Ssid_To_Aliyun(IPAddress ip,String ssid)
{
    if(connect_to_aliyun_flag == true)
    {
        char param[100];
        char jsonbuf[200];

        sprintf(param,"{\"IPAddress\":{\"value\":\"%s\"},\"WifiName\":{\"value\":\"%s\"}}",ip.toString().c_str(),ssid.c_str());
    
        sprintf(jsonbuf,"{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}",param);
  
        if(client.publish(ALIYUN_UPDATE_TOPIC,jsonbuf))
        {
            Serial.println("publish IP and SSId to Aliyun success");
            Serial.printf("Aliyun.cpp %d:ESP32 HEAP:%d\r\n",__LINE__,esp_get_free_heap_size());
        }
        else
        {
            Serial.println("publish IP and SSID to aliyun fail");
        }
    }
}